﻿using HDJ.Framework.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HDJ.Framework.Core
{
    public static class PoolClassManager<T> where T : class, new()
    {
        static private Queue<T> queue = new Queue<T>();

        static public T New()
        {
            T t;
            if (queue.Count > 0)
            {
                // an allocated object is already available; just reset it
                t = queue.Dequeue();
             
            }
            else
            {
                // no allocated object is available
                t = new T();
                IInit p = t as IInit;
                if (p != null)
                {
                    p.Init();
                }
            }
            return t;
        }

        static public void Recycle(T t)
        {
                queue.Enqueue(t);
            IReset poolFunction = t as IReset;
            if (poolFunction != null)
            {
                poolFunction.Reset();
            }
        }

        static public void Clear()
        {
            if (queue != null)
                queue.Clear();
        }
    }
    public static class PoolClassManager
    {
        private static Dictionary<Type, Queue> dataDic = new Dictionary<Type, Queue>();

        public static object New(Type type)
        {
            Queue queue = null;
            object t = null; ;
            if (dataDic.ContainsKey(type))
            {
                queue = dataDic[type];
                if (queue.Count > 0)
                {
                    t = queue.Dequeue();
                   
                    return t;
                }
            }

            t = ReflectionUtils.CreateDefultInstance(type);
            IInit p = t as IInit;
            if (p != null)
            {
                p.Init();
            }
            return t;
        }
        public static T New<T>() where T : class, new()
        {
            T t = (T)New(typeof(T)); 
            return t;
        }

        public static void Recycle(object t)
        {
            Type type = t.GetType();
            Queue queue = null;
            if (dataDic.ContainsKey(type))
            {
                queue = dataDic[type];
            }
            else
            {
                queue = new Queue();
                dataDic.Add(type, queue);
            }
            queue.Enqueue(t);
            IReset p = t as IReset;
            if (p != null)
            {
                p.Reset();
            }

        }

        public static void Clear()
        {
            if (dataDic != null)
                dataDic.Clear();
        }
    }

    public interface IReset
    {
        void Reset();
    }
    public interface IInit
    {
        void Init();
    }
}
